import axios from 'axios'
import JsSha from 'jssha'
import api from "@/common/api"
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
export default {
  reqData: function (url, data, res, err) {
    axios.post(url, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).then(res, err)
  },
  getPasswords: function (password) {
    let shaobj = new JsSha('SHA-1', 'TEXT')
    shaobj.update(password)
    return shaobj.getHash('HEX')
  },
  GetIndex (arr, min) {
    /**
     * 获取 特定点 与 线段距离最短的 index 值
     */
    let index = null;
    for(var i=0;i<arr.length;i++){
      if(arr[i] == min){
        index = i;
        break;
      }
    }
    return index;
  },
  GetTranslate (a, b) {
    /**
     * 获取2个定位点的长度
     */
    var ablng = Math.abs(a.lng - b.lng);
    var ablat = Math.abs(a.lat - b.lat);
    return Math.sqrt(ablng * ablng + ablat * ablat);
  },
  openMap: function (opt, flag) {
    // webview
    var w = plus.webview.create('./static/maps/maps.html', 'mapsId', {
      position: 'absolute',
      top: '45px',
      left: 0,
      right: 0,
      bottom: 0
    }, {
      preload: {
        option: opt,
        flag: flag // 0 司机 1 乘客
      }
    })
    w.show() // 显示窗口
  },
  distanceCompute: function (self, target, radius, completed, outRAIL) {
   // console.log('计算经纬度');
    //alert("后台半径："+radius);
    //alert("订单经纬度："+self.longitude+","+self.latitude);
    //alert("定位经纬度："+target.longitude+","+target.latitude);
    let selfPoint = new plus.maps.Point(self.longitude, self.latitude)
    let targetPoint = new plus.maps.Point(target.longitude, target.latitude)
     //alert(selfPoint+"_"+targetPoint);
     //alert(selfPoint.longitude+"_"+selfPoint.latitude);
    // alert(targetPoint.longitude+"_"+targetPoint.latitude);
    if(!self.latitude && !self.longitude){
      // alert("该订单没经纬度");
      return;
    }
    if(!target.latitude && !target.longitude){
      // alert("未获取经纬度");
      return;
    }
    plus.maps.Map.calculateDistance(targetPoint, selfPoint, function (event) {
      var distance = event.distance // 转换后的距离值
      //console.log('当前半径:' + radius + '距离:' + distance)
      if (parseInt(radius) >= distance) {
        // 在半径内
        console.log('在半径内');
        completed()
      } else {
        console.log('在半径外');
        // 在半径外
        typeof outRAIL === 'function' ? outRAIL() : false
      }
    }, function (e) {
      console.log('Failed:' + JSON.stringify(e))
    })
  },
  GetDeviation (pointArr) {
  },
  tts (text) {
    // if (window.mytts) { console.log("音频是否播放完毕:", window.mytts.ended), window.mytts.pause() }
    // window.mytts = new Audio('http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex=' + text)
    // window.mytts.play()

    // var msg = new SpeechSynthesisUtterance(text);
    //     // msg.rate = 1; //播放语速
    //     // msg.pitch = 10; //音调高低
    //     // msg.text = "播放文本";
    //     // msg.volume = 0.5; //播放音量
    //     window.speechSynthesis.speak(msg);

    this.reqData(api.app('getAudioToken'), {}, res=>{
      console.log(res.data.status)
      if(res.data.status == 100){
        useAudio(text, res.data.content.token)
      }
    },err =>{
      console.log(err)
    });
  },
  printVal(json,res){
    let mac_address = localStorage.getItem("bleId");
      console.log('打印测试'+mac_address);
      if (!mac_address && window.bluetoothTips) {
        alert('未选择蓝牙打印机');
        window.bluetoothTips = false;
        return;
      }
      var main = plus.android.runtimeMainActivity();
      var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
      var UUID = plus.android.importClass("java.util.UUID");
      var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
      var BAdapter = BluetoothAdapter.getDefaultAdapter();
      var device = BAdapter.getRemoteDevice(mac_address);
      plus.android.importClass(device);
      var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
      plus.android.importClass(bluetoothSocket);

      if (!bluetoothSocket.isConnected()) {
        console.log('检测到设备未连接，尝试连接....');
        bluetoothSocket.connect();
      }

      console.log('设备已连接'+bluetoothSocket.isConnected());

      if (bluetoothSocket.isConnected()) {
        var outputStream = bluetoothSocket.getOutputStream();
        plus.android.importClass(outputStream);
        console.log("getInputStream蓝牙输出流:"+JSON.stringify(outputStream));
        var getInputStream = bluetoothSocket.getInputStream();
        plus.android.importClass(getInputStream);
        console.log("getInputStream蓝牙获取流:"+JSON.stringify(getInputStream));
        // var bytes = plus.android.invoke(string, 'getBytes', 'UTF-8');
        // outputStream.write(bytes);
        // outputStream.flush();
        // device = null //这里关键
        // bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
        (res && res instanceof Function) && res();
      }
  },
  /**
   * html5+ 串口蓝牙操作
   */
  BluetoothTool() {
    let BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
    let Intent = plus.android.importClass("android.content.Intent");
    let IntentFilter = plus.android.importClass("android.content.IntentFilter");
    let BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
    let UUID = plus.android.importClass("java.util.UUID");
    let Toast = plus.android.importClass("android.widget.Toast");
    //连接串口设备的 UUID
    let MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    let invoke = plus.android.invoke;
    let btAdapter = BluetoothAdapter.getDefaultAdapter();
    let activity = plus.android.runtimeMainActivity();

    let btSocket = null;
    let btInStream = null;
    let btOutStream = null;
    let setIntervalId = 0;
    let btInputReaderStream = null;
    let btBufferReader = null;

    let btFindReceiver = null; //蓝牙搜索广播接收器
    let btStatusReceiver = null; //蓝牙状态监听广播

    let bytesNumber = 0; // 有多少个字节读取

    let state = {
      bluetoothEnable: false, //蓝牙是否开启
      bluetoothState: "", //当前蓝牙状态
      discoveryDeviceState: false, //是否正在搜索蓝牙设备
      readThreadState: false, //数据读取线程状态
    };

    let options = {
      /**
       * 监听蓝牙状态回调
       * @param {String} state
       */
      listenBTStatusCallback: function(state) {},
      /**
       * 搜索到新的蓝牙设备回调
       * @param {Device} newDevice
       */
      discoveryDeviceCallback: function(newDevice) {},
      /**
       * 蓝牙搜索完成回调
       */
      discoveryFinishedCallback: function() {},
      /**
       * 接收到数据回调
       * @param {Array} dataByteArr
       */
      readDataCallback: function(dataByteArr) {},
      /**
       * 蓝牙连接中断回调
       * @param {Exception} e
       */
      connExceptionCallback: function(e) {}
    }

    let bluetoothToolInstance = {
      state: state, //蓝牙状态
      init: init, //初始化回调函数
      isSupportBluetooth: isSupportBluetooth,
      getBluetoothStatus: getBluetoothStatus,
      turnOnBluetooth: turnOnBluetooth,
      turnOffBluetooth: turnOffBluetooth,
      getPairedDevices: getPairedDevices,
      discoveryNewDevice: discoveryNewDevice,
      listenBluetoothStatus: listenBluetoothStatus,
      connDevice: connDevice,
      disConnDevice: disConnDevice,
      cancelDiscovery: cancelDiscovery,
      readData: readData,
      sendData: sendData
    }
    if(window.bluetoothToolInstance) {
      return window.bluetoothToolInstance;
    } else {
      window.bluetoothToolInstance = bluetoothToolInstance;
      return bluetoothToolInstance;
    }

    function init(setOptions) {
      Object.assign(options, setOptions);
      state.bluetoothEnable = getBluetoothStatus();
      listenBluetoothStatus();
    }

    function shortToast(msg) {
      Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 是否支持蓝牙
     * @return {boolean}
     */
    function isSupportBluetooth() {
      if(btAdapter != null) {
        return true;
      }
      return false;
    }
    /**
     * 获取蓝牙的状态
     * @return {boolean} 是否已开启
     */
    function getBluetoothStatus() {
      if(btAdapter != null) {
        return btAdapter.isEnabled();
      }
      return false;
    }

    /**
     * 打开蓝牙
     * @param activity
     * @param requestCode
     */
    function turnOnBluetooth() {
      if(btAdapter == null) {
        shortToast("没有蓝牙");
        return;
      }
      if(!btAdapter.isEnabled()) {
        if(activity == null) {
          shortToast("未获取到activity");
          return;
        } else {
          let intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          let requestCode = 1;
          activity.startActivityForResult(intent, requestCode);
          return;
        }
      } else {
        shortToast("蓝牙已经打开");
      }
    }

    /**
     * 关闭蓝牙
     */
    function turnOffBluetooth() {
      if(btAdapter != null && btAdapter.isEnabled()) {
        btAdapter.disable();
      }
      if(btFindReceiver != null) {
        try {
          activity.unregisterReceiver(btFindReceiver);
        } catch(e) {

        }
        btFindReceiver = null;
      }
      state.bluetoothEnable = false;
      cancelDiscovery();
      closeBtSocket();

      if(btAdapter != null && btAdapter.isEnabled()) {
        btAdapter.disable();
        shortToast("蓝牙关闭成功");
      } else {
        shortToast("蓝牙已经关闭");
      }
    }

    /**
     * 获取已经配对的设备
     * @return {Array} connetedDevices
     */
    function getPairedDevices() {
      let pairedDevices = [];

      //蓝牙连接android原生对象，是一个set集合
      let pairedDevicesAndroid = null;
      if(btAdapter != null && btAdapter.isEnabled()) {
        pairedDevicesAndroid = btAdapter.getBondedDevices();
      } else {
        shortToast("蓝牙未开启");
      }

      if(!pairedDevicesAndroid) {
        return pairedDevices;
      }

      //遍历连接设备的set集合，转换为js数组
      let it = invoke(pairedDevicesAndroid, "iterator");
      while(invoke(it, "hasNext")) {
        let device = invoke(it, "next");
        pairedDevices.push({
          "name": invoke(device, "getName"),
          "address": invoke(device, "getAddress")
        });
      }
      return pairedDevices;
    }

    /**
     * 发现设备
     */
    function discoveryNewDevice() {
      if(btFindReceiver != null) {
        try {
          activity.unregisterReceiver(btFindReceiver);
        } catch(e) {
          console.error(e);
        }
        btFindReceiver = null;
        cancelDiscovery();
      }
      let Build = plus.android.importClass("android.os.Build");

      //6.0以后的如果需要利用本机查找周围的wifi和蓝牙设备, 申请权限
          if(Build.VERSION.SDK_INT >= 6.0){

          }

      btFindReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
        "onReceive": function(context, intent) {
          plus.android.importClass(context);
          plus.android.importClass(intent);
          let action = intent.getAction();

          if(BluetoothDevice.ACTION_FOUND == action) { // 找到设备
            let device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            let newDevice = {
              "name": plus.android.invoke(device, "getName"),
              "address": plus.android.invoke(device, "getAddress")
            }
            options.discoveryDeviceCallback && options.discoveryDeviceCallback(newDevice);
          }
          if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) { // 搜索完成
            cancelDiscovery();
            options.discoveryFinishedCallback && options.discoveryFinishedCallback();
          }
        }
      });
      let filter = new IntentFilter();
      filter.addAction(BluetoothDevice.ACTION_FOUND);
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
      activity.registerReceiver(btFindReceiver, filter);
      btAdapter.startDiscovery(); //开启搜索
      state.discoveryDeviceState = true;
    }

    /**
     * 蓝牙状态监听
     * @param {Activity} activity
     */
    function listenBluetoothStatus() {
      if(btStatusReceiver != null) {
        try {
          activity.unregisterReceiver(btStatusReceiver);
        } catch(e) {
          console.error(e);
        }
        btStatusReceiver = null;
      }

      btStatusReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
        "onReceive": function(context, intent) {
          plus.android.importClass(context);
          plus.android.importClass(intent);

          let action = intent.getAction();
          switch(action) {
            case BluetoothAdapter.ACTION_STATE_CHANGED:
              let blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
              let stateStr = "";
              switch(blueState) {
                case BluetoothAdapter.STATE_TURNING_ON:
                  stateStr = "STATE_TURNING_ON";
                  break;
                case BluetoothAdapter.STATE_ON:
                  state.bluetoothEnable = true;
                  stateStr = "STATE_ON";
                  break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                  stateStr = "STATE_TURNING_OFF";
                  break;
                case BluetoothAdapter.STATE_OFF:
                  stateStr = "STATE_OFF";
                  state.bluetoothEnable = false;
                  break;
              }
              state.bluetoothState = stateStr;
              options.listenBTStatusCallback && options.listenBTStatusCallback(stateStr);
              break;
          }
        }
      });
      let filter = new IntentFilter();
      filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
      activity.registerReceiver(btStatusReceiver, filter);
    }

    /**
     * 根据蓝牙地址，连接设备
     * @param {Stirng} address
     * @return {Boolean}
     */
    function connDevice(address, fun) {
      let InputStream = plus.android.importClass("java.io.InputStream");
      let OutputStream = plus.android.importClass("java.io.OutputStream");
      let BluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");

      cancelDiscovery();
      if(btSocket != null) {
        closeBtSocket();
      }
      state.readThreadState = false;

      try {
        let device = invoke(btAdapter, "getRemoteDevice", address);
        btSocket = invoke(device, "createRfcommSocketToServiceRecord", MY_UUID);
      } catch(e) {
        console.error(e);
        shortToast("连接失败，获取Socket失败！");
        return false;
      }
      try {
        invoke(btSocket, "connect");
        readData(); //读数据
        shortToast("连接成功");
        fun && fun();
      } catch(e) {
        console.error(e);
        shortToast("连接失败");
        // fun && fun();
        // fun();
        try {
          btSocket.close();
          btSocket = null;
        } catch(e1) {
          console.error(e1);
        }
        return false;
      }
      return true;
    }

    /**
     * 断开连接设备
     * @param {Object} address
     * @return {Boolean}
     */
    function disConnDevice() {
      if(btSocket != null) {
        closeBtSocket();
      }
      state.readThreadState = false;
      shortToast("断开连接成功");
    }

    /**
     * 断开连接设备
     * @param {Object} address
     * @return {Boolean}
     */
    function closeBtSocket() {
      state.readThreadState = false;
      if(!btSocket) {
        return;
      }
      try {
        btSocket.close();
      } catch(e) {
        console.error(e);
        btSocket = null;
      }
    }

    /**
     * 取消发现
     */
    function cancelDiscovery() {
      if(btAdapter.isDiscovering()) {
        btAdapter.cancelDiscovery();
      }
      if(btFindReceiver != null) {
        activity.unregisterReceiver(btFindReceiver);
        btFindReceiver = null;
      }
      state.discoveryDeviceState = false;
    }

    /**
     * 读取数据
     * @param {Object} activity
     * @param {Function} callback
     * @return {Boolean}
     */
    function readData() {
      if(!btSocket) {
        shortToast("请先连接蓝牙设备！");
        return false;
      }
      try {
        btInStream = invoke(btSocket, "getInputStream");
        btOutStream = invoke(btSocket, "getOutputStream");
        // console.log('---创建reader流---');
        // btInputReaderStream = plus.android.newObject("java.io.InputStreamReader", btInStream);
        // console.log('---创建buffer---');
        // btBufferReader = plus.android.newObject("java.io.BufferedReader", btInputReaderStream);
        // console.log("创建完毕----")
      } catch(e) {
        console.error(e);
        shortToast("创建输入输出流失败！");
        closeBtSocket();
        return false;
      }
      let setTimeCount = 0;
      read();
      state.readThreadState = true;
      return true;

      /**
       * 模拟多线程read
       */
      function read() {
        console.log('---开始读取---');
        clearInterval(setIntervalId);
        setIntervalId = setInterval(function() {
          setTimeCount++;
          if(state.readThreadState) {
            let t = new Date().getTime();
            //心跳检测
            if(setTimeCount % 20 == 0) {
              try {
                btOutStream.write([0b00]);
              } catch(e) {
                state.readThreadState = false;
                options.connExceptionCallback && options.connExceptionCallback(e);
              }
            }
            let dataArr = [];
            // console.log("蓝牙读取回调数据00000：---" + "----");
            // let datass = invoke(btInStream, "read", plus.android.newObject('byte', "1024"));
            // let datass = invoke(btInStream, "read", new ArrayBuffer(1024));
            // console.log("蓝牙读取回调数据11111：---" + JSON.stringify(datass) + "----");
            let dl=invoke(btInStream, "available");
            while(dl !== 0) {
              for(let i=0;i<dl;i++){
                let data = invoke(btInStream, "read");
                // let dddd = invoke(btBufferReader, 'readLine');
                // console.log("蓝牙读取回调数据readeredbuffer----", JSON.stringify(dddd));
                // console.log("蓝牙读取回调数据22222：---" + JSON.stringify(data) + "----");
                dataArr.push(data);
              }
              let ct = new Date().getTime();
              if(ct - t > 20) {
                break;
              }
              dl=invoke(btInStream, "available");
            }
            if(dataArr.length > 0) {
              options.readDataCallback && options.readDataCallback(dataArr);
            }
          }
        }, 5);
      }

    }

    /**
     * 发送数据
     * @param {String} dataStr
     * @return {Boolean}
     */
    function sendData(dataStr) {
      if(!btOutStream) {
        shortToast("创建输出流失败！");
        return;
      }
      let bytes = invoke(dataStr, 'getBytes', 'utf-8');
      try {
        btOutStream.write(bytes);
      } catch(e) {
        return false;
      }
      return true;
    }
  }
}

/**
 * 浏览器调用语音合成接口
 * @param {Object} param 百度语音合成接口参数
 * 请参考 https://ai.baidu.com/docs#/TTS-API/41ac79a6
 * @param {Object} options 跨域调用api参数
 *           timeout {number} 超时时间 默认不设置为60秒
 *           volume {number} audio控件音量，范围 0-1
 *           hidden {boolean} 是否隐藏audio控件
 *           autoDestory {boolean} 播放音频完毕后是否自动删除控件
 *           onInit {Function} 创建完audio控件后调用
 *           onSuccess {Function} 远程语音合成完成，并且返回音频文件后调用
 *           onError {Function}  远程语音合成完成，并且返回错误字符串后调用
 *           onTimeout {Function} 超时后调用，默认超时时间为60秒
 */

function useAudio(text, token){
  btts({
    tex: text,
    tok: token,
    spd: 5,
    pit: 5,
    vol: 15,
    per: 0
  }, {
    volume: 0.3,
    autoDestory: true,
    timeout: 10000,
    hidden: false,
    onInit: function (htmlAudioElement) {
      console.log(htmlAudioElement)
      htmlAudioElement.play();
    },
    onSuccess: function(htmlAudioElement) {
      console.log(htmlAudioElement)
    },
    onError: function(errorText) {
      console.log(errorText)
      getToken(text)
    },
    onTimeout: function (e) {
      console.log(e)
    }
  });
}
function btts(param, options) {
  var url = 'http://tsn.baidu.com/text2audio';
  var opt = options || {};
  var p = param || {};

  // 如果浏览器支持，可以设置autoplay，但是不能兼容所有浏览器
  var audio = document.createElement('audio');
  if (opt.autoplay) {
      audio.setAttribute('autoplay', 'autoplay');
  }

  // 隐藏控制栏
  if (!opt.hidden) {
      audio.setAttribute('controls', 'controls');
  } else {
      audio.style.display = 'none';
  }

  // 设置音量
  if (typeof opt.volume !== 'undefined') {
      audio.volume = opt.volume;
  }

  // 调用onInit回调
  isFunction(opt.onInit) && opt.onInit(audio);

  // 默认超时时间60秒
  var DEFAULT_TIMEOUT = 60000;
  var timeout = opt.timeout || DEFAULT_TIMEOUT;

  // 创建XMLHttpRequest对象
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url);

  // 创建form参数
  var data = {};
  for (var p in param) {
      data[p] = param[p]
  }

  // 赋值预定义参数
  data.cuid = data.cuid || data.tok;
  data.ctp = 1;
  data.lan = data.lan || 'zh';
  data.aue = data.aue || 3;

  // 序列化参数列表
  var fd = [];
  for(var k in data) {
      fd.push(k + '=' + encodeURIComponent(data[k]));
  }

  // 用来处理blob数据
  var frd = new FileReader();
  xhr.responseType = 'blob';
  xhr.send(fd.join('&'));

  // 用timeout可以更兼容的处理兼容超时
  var timer = setTimeout(function(){
      xhr.abort();
      isFunction(opt.onTimeout) && opt.onTimeout();
  }, timeout);

  xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
          clearTimeout(timer);
          if (xhr.status == 200) {
              if (xhr.response.type === 'audio/mp3') {

                  // 在body元素下apppend音频控件
                  document.body.appendChild(audio);

                  audio.setAttribute('src', URL.createObjectURL(xhr.response));

                  // autoDestory设置则播放完后移除audio的dom对象
                  if (opt.autoDestory) {
                      audio.onended = function() {
                          document.body.removeChild(audio);
                      }
                  }

                  isFunction(opt.onSuccess) && opt.onSuccess(audio);
              }

              // 用来处理错误
              if (xhr.response.type === 'application/json') {
                  frd.onload = function(){
                      var text = frd.result;
                      isFunction(opt.onError) && opt.onError(text);
                  };
                  frd.readAsText(xhr.response);
              }
          }
      }
  }

  // 判断是否是函数
  function isFunction(obj) {
      if (Object.prototype.toString.call(obj) === '[object Function]') {
          return true;
      }
      return false;
  }
}
